package com.xman.lib.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpClientHelper {

	// Construct a query string
	public static String queryString(String url,
			Map<String, Object> parameters, boolean needEncode) {
		StringBuilder fullUrl = new StringBuilder(url);
		if (parameters != null && parameters.keySet().size() > 0) {
			if (!url.contains("?"))
				fullUrl.append("?"); // Only append ? if absent
			int count = 0;
			for (String key : parameters.keySet()) {
				if (parameters.get(key) != null) {
					if (needEncode) {
						fullUrl.append(URLEncoder.encode(key));
						fullUrl.append("=");
						fullUrl.append(URLEncoder.encode(parameters.get(key)
								.toString()));
					} else {
						fullUrl.append(key);
						fullUrl.append("=");
						fullUrl.append(parameters.get(key));
					}
					count++;
					if (count < parameters.keySet().size())
						fullUrl.append("&");
				}
			}
		}
		return fullUrl.toString();
	}

	// Construct a query string
	public static String queryString(String url, Map<String, Object> parameters) {
		StringBuilder fullUrl = new StringBuilder(url);
		if (parameters != null && parameters.keySet().size() > 0) {
			if (!url.contains("?"))
				fullUrl.append("?"); // Only append ? if absent
			int count = 0;
			for (String key : parameters.keySet()) {
				if (parameters.get(key) != null) {
					fullUrl.append(URLEncoder.encode(key));
					fullUrl.append("=");
					fullUrl.append(URLEncoder.encode(parameters.get(key)
							.toString()));
					count++;
					if (count < parameters.keySet().size())
						fullUrl.append("&");
				}
			}
		}
		return fullUrl.toString();
	}

	// Construct an encoded form entity
	public static HttpEntity encodedFormEntity(Map<String, Object> parameters) {
		HttpEntity entity = null;
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		if (parameters != null) {
			for (String key : parameters.keySet()) {
				pairs.add(new BasicNameValuePair(key, parameters.get(key)
						.toString()));
			}
			try {
				// Note - we should never get an encoding exception
				entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
			} catch (UnsupportedEncodingException e) {
			}
		}
		return entity;
	}

}
